package com.htthorizon.util;

import com.alibaba.cloudapi.sdk.client.ApacheHttpClient;
import com.alibaba.cloudapi.sdk.enums.HttpMethod;
import com.alibaba.cloudapi.sdk.enums.ParamPosition;
import com.alibaba.cloudapi.sdk.enums.Scheme;
import com.alibaba.cloudapi.sdk.model.ApiRequest;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Brilliant
 */
@Component
@Slf4j
public class SDKGetAPIUtil extends ApacheHttpClient {

    @Value("${serviceMarket.host}")
    private  String host;

    public void init(HttpClientBuilderParams httpClientBuilderParams){
        httpClientBuilderParams.setScheme(Scheme.HTTP);
        httpClientBuilderParams.setHost(host);
        super.init(httpClientBuilderParams);
    }


    public ApiResponse getMetaDataByTb(String path, String tb){
        ApiRequest request = new ApiRequest(HttpMethod.GET , path);
        request.addParam("pageNum" , "1" , ParamPosition.QUERY , true);
        request.addParam("pageSize" , "2000" , ParamPosition.QUERY , true);
        request.addParam("model_tb",tb, ParamPosition.QUERY , true);
        return sendSyncRequest(request);
    }

    public ApiResponse searchByParams(String path, Map<String,Object> params) throws UnsupportedEncodingException {
        ApiRequest request = new ApiRequest(HttpMethod.GET , path);
        for (Map.Entry<String,Object> entry : params.entrySet()){
            log.info("参数顺序:{}-{}",entry.getKey(),entry.getValue().toString());
            request.addParam(entry.getKey(), entry.getValue().toString(), ParamPosition.PATH, true);
        }
        return sendSyncRequest(request);
    }

// todo 超出页数的情况
    public ApiResponse searchByParams2(String path) {
        ApiRequest request = new ApiRequest(HttpMethod.GET , path);
        request.addParam("pageNum","1", ParamPosition.QUERY, true);
        request.addParam("pageSize","2000", ParamPosition.QUERY, true);
        return sendSyncRequest(request);
    }

    public ApiResponse searchByParams3(String path,String pageNum,String pageSize) {
        ApiRequest request = new ApiRequest(HttpMethod.GET , path);
        request.addParam("pageNum",pageNum, ParamPosition.QUERY, true);
        request.addParam("pageSize",pageSize, ParamPosition.QUERY, true);
        return sendSyncRequest(request);
    }
}
